package chaincode

import (
	"encoding/json"
	"fmt"

	"github.com/hyperledger/fabric-contract-api-go/contractapi"
)

const KEY = "dog-count"

// 智能合约类
type SmartContract struct {
	contractapi.Contract
}

type Asset struct {
	Count int `json:"count"`
}

func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error {
	asset := Asset{Count: 100}

	assetJSON, err := json.Marshal(asset)

	if err != nil {
		return err
	}

	err = ctx.GetStub().PutState(KEY, assetJSON)
	if err != nil {
		return fmt.Errorf("failed to put to world state. %v", err)
	}
	return nil
}

func (s *SmartContract) CountDogs(ctx contractapi.TransactionContextInterface) (*Asset, error) {
	assetJSON, err := ctx.GetStub().GetState(KEY)

	if err != nil {
		return nil, fmt.Errorf("failed to put to world state. %v", err)
	}

	if assetJSON == nil {
		return nil, fmt.Errorf("the asset %s does not exist", KEY)
	}

	var asset Asset

	err = json.Unmarshal(assetJSON, &asset)

	if err != nil {
		return nil, err
	}
	return &asset, nil
}

//添加小dog
func (s *SmartContract) NewDogs(ctx contractapi.TransactionContextInterface, add_count int) error {
	asset, err := s.CountDogs(ctx)
	if err != nil {
		return err
	}

	asset.Count += add_count

	assetJSON, err := json.Marshal(asset)

	if err != nil {
		return err
	}
	return ctx.GetStub().PutState(KEY, assetJSON)

}
